import time

from flask import *
from flask_restful import Api, Resource, reqparse

from models.model import *
from utils.JwtTool import JwtTool
from utils.QiniuTool import QiniuTool
from utils.RongTool import RongTool
import random

view_bp = Blueprint('view_bp', __name__)
api = Api(view_bp)



# 装饰器
def login(fonc):
    def end(*args, **kwargs):
        if not g.id:
            return jsonify({'code': 403, 'msg': '未通过认证，请登录'})
        elif g.id == -1:
            return jsonify({'code': 405, 'msg': 'token已被禁用'})
        elif g.id == -2:
            return jsonify({'code': 666, 'msg': 'token已过期'})

        return fonc(*args, **kwargs)
    return end



# 发送验证码
class SmsCodeView(Resource):
    def get(self):
        mobile = request.args.get('mobile')
        sms_code = str(random.randint(0, 9))
        ser = RongTool().sms_code(mobile, sms_code)
        if not ser:
            return jsonify({'code': 400, 'msg': '发送失败', 'sms_code': sms_code})
        return jsonify({'code': 200, 'msg': '已发送，请注意查收'})



api.add_resource(SmsCodeView, '/sms')


# 登录/注册
class UserView(Resource):
    def get(self):
        return '111111'

    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('mobile', required=True)
        req.add_argument('sms_code', required=True)
        req.add_argument('password', required=True)
        args = req.parse_args()

        # 判断用户是否存在
        user_info = UserModel.query.filter(UserModel.mobile == args['mobile']).first()
        if not user_info:
            # 判断验证码
            sms_code = RongTool().r.get(args['mobile'])
            if not sms_code:
                return jsonify({'code': 400, 'msg': '验证码已过期'})
            if sms_code.decode() != args['sms_code']:
                print(sms_code.decode(), args['sms_code'])
                return jsonify({'code': 400, 'msg': '验证码不一致'})

            # 注册
            db.session.add(UserModel(
                mobile=args['mobile'],
                name=f'游客{args["mobile"][-4:]}',
                password=args['password'],
                img='1'
            ))
            db.session.commit()

        # 登录
        user_info = UserModel.query.filter(UserModel.mobile == args['mobile']).first()

        # 判断密码
        if user_info.password != args['password']:
            return jsonify({'code': 400, 'msg': '密码不正确'})

        # 生成token
        token = JwtTool().jwt_token({
            'id': user_info.id,
            'mobile': user_info.mobile,
            'name': user_info.name
        })
        # 生成长token
        long_token = JwtTool().jwt_long_token({
            'id': user_info.id,
            'mobile': user_info.mobile,
            'name': user_info.name,
            'status': 1
        })

        return jsonify({'code': 200, 'msg': '登录成功', 'token': token, 'long_token': long_token})


api.add_resource(UserView, '/user')


# 上传图片
class UploadView(Resource):
    @login
    def post(self):
        img = request.files.get('img')

        # 拼接路由
        name = f'{str(int(time.time())) + str(random.randint(10000, 99999))}.{img.filename.split(".")[-1]}'
        static_path = f'static/{name}'
        print(static_path)

        # 保存到本地
        img.save(static_path)

        # 上传到七牛云
        ser = QiniuTool().upload(static_path, name)

        if not ser:
            return jsonify({'code': 400, 'msg': '上传图片失败'})
        return jsonify({'code': 200, 'msg': '上传成功', 'static_path': name})

api.add_resource(UploadView, '/upload')



# 作业的提交
class JobView(Resource):
    @login
    def get(self):
        job_all = JobModel.query.all()
        job_list = []
        for item in job_all:
            job_img_list = []
            for img in item.job_img:
                job_img_list.append({
                    'img': current_app.config.get('QINIU_HOST') + img.img
                })
            if item.user.img == '1':

                img = 'https://www.com8.cn/wp-content/uploads/2020/09/20200922022838-5f6961562471f.jpg'
            else:
                img = current_app.config.get('QINIU_HOST') + item.user.img

            job_list.append({
                'user': {
                    'name': item.user.name,
                    'img': img
                },
                'time': str(item.time),
                'title': item.title,
                'status': item.status,
                'img_list': job_img_list
            })

        return jsonify({'code': 200, 'list': job_list})

    @login
    def post(self):
        print('----', g.id)
        req = reqparse.RequestParser()
        req.add_argument('title', required=True)
        req.add_argument('img_list', required=True)
        args = req.parse_args()
        args['user_id'] = g.id
        print('pppppp', args['img_list'].split(','), type(args['img_list'].split(',')))

        # 添加数据
        job_info = JobModel.query.filter(JobModel.title == args['title'], JobModel.user_id == args['user_id']).first()
        if not job_info:
            db.session.add(JobModel(
                title=args['title'],
                user_id=args['user_id'],
            ))
            db.session.commit()

        job_info = JobModel.query.filter(JobModel.title == args['title'], JobModel.user_id == args['user_id']).first()

        for item in args['img_list'].split(','):
            db.session.add(JobImgModel(
                img=item,
                job_id=job_info.id
            ))
            db.session.commit()

        return jsonify({'code': 200, 'msg': '发送成功'})


api.add_resource(JobView, '/job')



# 禁用token
class TokenView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('token', location='headers')
        args = req.parse_args()

        RongTool().r.set(args['token'], '1', ex=3600)

        return jsonify({'code': 200, 'msg': '退出成功'})

api.add_resource(TokenView, '/token')


# 更新token
class UpdateToken(Resource):
    def put(self):
        token = JwtTool().jwt_token({
            'id': g.long['id'],
            'mobile': g.long['mobile'],
            'name': g.long['name']
        })

        return jsonify({'code': 200, 'token': token})


api.add_resource(UpdateToken, '/uptoken')












